package com.zoffy.ybuhelper.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SwitchCompat;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import com.zoffy.ybuhelper.MyApplication;
import com.zoffy.ybuhelper.R;
import com.zoffy.ybuhelper.adapter.AddCategoryRecyclerAdapter;
import com.zoffy.ybuhelper.dao.CategoryDao;
import com.zoffy.ybuhelper.dao.MenuCategoryDao;
import com.zoffy.ybuhelper.dao.MenuDao;
import com.zoffy.ybuhelper.dao.OriginDao;
import com.zoffy.ybuhelper.database.YBUDatabase;
import com.zoffy.ybuhelper.pojo.entity.Category;
import com.zoffy.ybuhelper.pojo.entity.Menu;
import com.zoffy.ybuhelper.pojo.entity.MenuCategory;
import com.zoffy.ybuhelper.pojo.entity.Origin;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class AddItemFragment extends DialogFragment {

    private View view;
    private List<Category> categoryList;
    //该列表用于储存菜品对应的种类
    private List<Category> addCategoryList = new ArrayList<>();
    private List<Origin> originList;
    private AddCategoryRecyclerAdapter addCategoryRecyclerAdapter;

    /**
     * 该属性用于表示当前是哪个种类的添加界面
     * 该值由父Fragment通过Bundle传递
     */
    private String type;
    private MenuDao menuDao;
    private CategoryDao categoryDao;
    private OriginDao originDao;
    private EditText itemName;
    private MenuCategoryDao menuCategoryDao;
    private Spinner originSpinner;
    private Spinner categorySpinner;
    private int targetId;
    private SwitchCompat switchCompat;
    private TextView deletedTextView;

    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_add_eat_item, null, false);
        type = getArguments().getString("type");
        init();
        return view;
    }

    private void init() {
        dbInit();
        layoutInit();
        spinnerInit();
        changeInit();
        recycleViewInit();
        buttonInit();

    }

    private void dbInit() {
        YBUDatabase YBUDatabase = MyApplication.getInstance().getYBUDatabase();
        menuDao = YBUDatabase.menuDao();
        categoryDao = YBUDatabase.categoryDao();
        originDao = YBUDatabase.originDao();
        menuCategoryDao = YBUDatabase.menuCategoryDao();
        originList = originDao.getAll();
        categoryList = categoryDao.getAll();
    }

    private void layoutInit() {
        originSpinner = view.findViewById(R.id.select_origin);
        categorySpinner = view.findViewById(R.id.select_category);
        itemName = view.findViewById(R.id.input_name);
        if ((!"menu".equals(type)) && (!"change_menu".equals(type))) {
            view.findViewById(R.id.origin_area).setVisibility(View.GONE);
            view.findViewById(R.id.category_area).setVisibility(View.GONE);
        }
        deletedTextView = view.findViewById(R.id.deleted_state);
        switchCompat = view.findViewById(R.id.deleted_switch);
        switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    deletedTextView.setText("启用");
                }
                else{
                    deletedTextView.setText("禁用");
                }
            }
        });
        LinearLayout deletedLinearLayout=view.findViewById(R.id.deleted_area);
        if(("category".equals(type)) || ("change_category".equals(type))){
            deletedLinearLayout.setVisibility(View.GONE);
        }
    }


    private void recycleViewInit() {
        if ((!"menu".equals(type)) && (!"change_menu".equals(type))) {
            return;
        }
        RecyclerView categoryRecyclerView = view.findViewById(R.id.category_recycler_view);
        addCategoryRecyclerAdapter = new AddCategoryRecyclerAdapter(addCategoryList);
        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        categoryRecyclerView.setLayoutManager(staggeredGridLayoutManager);
        categoryRecyclerView.setAdapter(addCategoryRecyclerAdapter);
    }

    private void spinnerInit() {
        spinnerInitThis(originSpinner, originList.stream().map(Origin::getName).collect(Collectors.toList()));
        spinnerInitThis(categorySpinner, categoryList.stream().map(Category::getName).collect(Collectors.toList()));
    }

    private void buttonInit() {
        Button addTagButton = view.findViewById(R.id.add_tag);
        addTagButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = categorySpinner.getSelectedItemPosition();
                Category category = categoryList.get(position);
                addCategoryRecyclerAdapter.addItem(new Category(category.getId(), category.getName()));
            }
        });

        Button addEatButton = view.findViewById(R.id.add_eat);
        addEatButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (itemName.getText().toString().equals("")) {
                    Toast.makeText(AddItemFragment.this.getContext(), "名称不能为空", Toast.LENGTH_LONG).show();
                    return;
                }
                switch (type) {
                    case "menu":
                        addMenu();
                        break;
                    case "origin":
                        addOrigin();
                        break;
                    case "category":
                        addCategory();
                        break;
                    case "change_menu":
                        changeMenu();
                        break;
                    case "change_origin":
                        changeOrigin();
                        break;
                    case "change_category":
                        changeCategory();
                        break;
                    default:
                        break;
                }
                UpdateFragment parent = (UpdateFragment) getParentFragment();
                parent.update();
                getParentFragmentManager().beginTransaction().remove(AddItemFragment.this).commit();
            }
        });
    }

    private void changeInit() {
        Bundle arguments = getArguments();

        switch (type) {
            case "change_menu":
                targetId = arguments.getInt("id");
                Menu menu = menuDao.queryById(targetId);
                if(menu.getDeleted()==0){
                    deletedTextView.setText("启用");
                    switchCompat.setChecked(true);
                }
                else{
                    deletedTextView.setText("禁用");
                    switchCompat.setChecked(false);
                }
                itemName.setText(menu.getName());
                for (int position = 0; position < originList.size(); position++) {
                    Origin origin = originList.get(position);
                    if (origin.getId().equals(menu.getOriginId())) {
                        originSpinner.setSelection(position, true);
                        break;
                    }

                }
                addCategoryList = categoryDao.queryByMenuId(targetId);
                break;
            case "change_origin":
                targetId = arguments.getInt("id");
                Origin origin= originDao.get(targetId);
                if(origin.getDeleted()==0){
                    deletedTextView.setText("启用");
                    switchCompat.setChecked(true);
                }
                else{
                    deletedTextView.setText("禁用");
                    switchCompat.setChecked(false);
                }
                itemName.setText(origin.getName());
                break;
            case "change_category":
                targetId = arguments.getInt("id");
                Category category=categoryDao.get(targetId);
                itemName.setText(category.getName());
                break;
            default:
                break;
        }
    }

    private <T> void spinnerInitThis(Spinner spinner, List<T> list) {
        ArrayAdapter<T> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item);
        adapter.addAll(list);
        adapter.setDropDownViewResource(androidx.constraintlayout.widget.R.layout.support_simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
    }

    private void addMenu() {
        if (originList.size() == 0) {
            Toast.makeText(getContext(), "在添加菜品前，你至少需要有一个商家", Toast.LENGTH_LONG).show();
            return;
        }
        Spinner originSpinner = view.findViewById(R.id.select_origin);

        int position = originSpinner.getSelectedItemPosition();
        String name = itemName.getText().toString();
        int deleted;
        if(switchCompat.isChecked()){
            deleted=0;
        }
        else{
            deleted=1;
        }
        Menu menu = new Menu();
        menu.setName(name);
        menu.setOriginId(originList.get(position).getId());
        menu.setDeleted(deleted);
        //获取新生成的对象的自增id
        long lastInsertPosition = menuDao.insert(menu);
        for (Category category : addCategoryRecyclerAdapter.getAll()) {
            MenuCategory menuCategory = new MenuCategory((int) lastInsertPosition, category.getId());
            menuCategoryDao.insert(menuCategory);
        }


    }

    private void addOrigin() {
        Origin origin = new Origin();
        String name = itemName.getText().toString();
        int deleted;
        if(switchCompat.isChecked()){
            deleted=0;
        }
        else{
            deleted=1;
        }
        origin.setName(name);
        origin.setDeleted(deleted);
        originDao.insert(origin);
    }

    private void addCategory() {
        Category category = new Category();
        String name = itemName.getText().toString();
        category.setName(name);
        categoryDao.insert(category);
    }

    private void changeMenu() {
        String name = itemName.getText().toString();
        menuDao.updateName(targetId, name);
        int originId = originList.get(originSpinner.getSelectedItemPosition()).getId();
        menuDao.updateOriginId(targetId,originId);
        menuCategoryDao.deleteByMenuId(targetId);
        for (Category category : addCategoryList) {
            menuCategoryDao.insert(new MenuCategory(targetId, category.getId()));
        }

        int deleted;
        if(switchCompat.isChecked()){
            deleted=0;
        }
        else{
            deleted=1;
        }
        menuDao.updateDeleted(targetId,deleted);
    }

    private void changeOrigin() {
        String name=itemName.getText().toString();
        originDao.updateName(targetId,name);

        int deleted;
        if(switchCompat.isChecked()){
            deleted=0;
        }
        else{
            deleted=1;
        }
        originDao.updateDeleted(targetId,deleted);
    }

    private void changeCategory() {
        String name=itemName.getText().toString();
        categoryDao.updateName(targetId,name);
    }
}
